//
//  CreateMyAccount.m
//  Bespoke
//
//  Created by Cheng on 12/9/17.
//
//

#import "CreateMyAccount.h"
#import "GDataXMLNode.h"
#import "AccountParser.h"
#import "BK_Enviroment.h"
#import "RequestAPIFunction.h"
#import "AccountInfo.h"
#import "LoadingUI.h"

#define LOADINGVIEW_TAG 10000000
#define LOADINGIMAGE_TAG 20000000

#define NEWUSER_API @"http://54.235.166.43/BeSpokeAPI/newUser.php"
#define USERINFO_API @"http://54.235.166.43/BeSpokeAPI/userInfo.php"

@implementation CreateMyAccount
@synthesize Tf_FullName,Tf_Email, Tf_Password, BK_En_object, Array_AccountInfo;
@synthesize delegate;


-(IBAction)CancelPressed:(id)sender {
    [delegate CancelPressed_CreateMyAccount];
}

- (IBAction)CreateAccountPressed:(id)sender {
    
    [Tf_FullName resignFirstResponder];
    [Tf_Email resignFirstResponder];
    [Tf_Password resignFirstResponder];
    
    if (([Tf_FullName.text isEqualToString:@""])||(Tf_FullName.text==nil)) {
        UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Please enter Full Name." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [AlertView show];
        return;
    }
    else if (([Tf_Email.text isEqualToString:@""])||(Tf_Email.text==nil)) {
        UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Please enter Email." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [AlertView show];
        return;
    }
    else if (([Tf_Password.text isEqualToString:@""])||(Tf_Password.text==nil)) {
        UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Please enter Password." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [AlertView show];
        return;
    }
    else if ([Tf_Email.text rangeOfString:@"@"].location == NSNotFound) {//Check username is or not Email.
        UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Please enter a valid email address." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [AlertView show];
        return;
    }
    
    
    [[NSOperationQueue mainQueue] addOperationWithBlock:
     ^(void) {
         
         [NSThread detachNewThreadSelector:@selector(threadStartAnimating) toTarget:self withObject:nil];
         
         //User XML requst API.
         NSData *responseData =
         [RequestAPIFunction XML_PostRequest:[NSString stringWithFormat:@"<AccountInfo UserName=\"%@\" Password=\"%@\" Name=\"%@\" Level=\"iPadUser\" Organization=\"Bespoke\" />",
                                              Tf_Email.text,
                                              Tf_Password.text,
                                              Tf_FullName.text]
                                   urlString:NEWUSER_API];
         
         //No Network Connection or time out.
         if (responseData == nil) {
             
             [NSThread detachNewThreadSelector:@selector(threadStopAnimating) toTarget:self withObject:nil];
             return;
         }
         
         NSError *error;
         GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:responseData options:0 error:&error];
         
         
         //Check to upload is success.
         if ([[doc nodesForXPath:@"//Registered" error:&error] count]!=0) {//Account Registered
             
             UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"An account already exists with that email address. Try again!" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
             AlertView.delegate = self;
             [AlertView show];
             
         }
         else if ([[doc nodesForXPath:@"//Success" error:&error] count]!=0) {
             
             NSData *responseData =
             [RequestAPIFunction XML_PostRequest:[NSString stringWithFormat:@"<Authentication UserName=\"%@\" Password=\"%@\" Name=\"\" Source=\"Bespoke\" Plaintext=\"True\" />",
                                                  Tf_Email.text,
                                                  Tf_Password.text]
                                       urlString:USERINFO_API];
             
             //No Network Connection or time out.
             if (responseData == nil)
                 return;
             
             self.Array_AccountInfo = [AccountParser loadAccountInfo:responseData];
             
             [BK_En_object setAuthenticationUserName:Tf_Email.text Password:Tf_Password.text];
             [BK_En_object setAccountInfoFullName:Tf_FullName.text setPartner:nil];
             [BK_En_object setAccountChannel:((AccountInfo *)[self.Array_AccountInfo objectAtIndex:0]).NS_Channel];
             
             UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Success" message:@"Registration has been successful." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
             AlertView.delegate = self;
             [AlertView setTag:101];
             [AlertView show];
         }
         
         [NSThread detachNewThreadSelector:@selector(threadStopAnimating) toTarget:self withObject:nil];

     }];
}

#pragma mark - UIAlertViewDelegate

- (void)didPresentAlertView:(UIAlertView *)alertView {
    [[self viewWithTag:103] removeFromSuperview];
    [[self viewWithTag:104] removeFromSuperview];
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    
    if (alertView.tag==101) {
        
        [delegate SignUpSuccess];
    }
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    if(textField == Tf_FullName)
        [Tf_Email becomeFirstResponder];
    else if(textField == Tf_Email)
        [Tf_Password becomeFirstResponder];
    else if(textField == Tf_Password)
        [self CreateAccountPressed:textField];
    return YES;
}

#pragma mark - LoadingUI

-(void)threadStartAnimating {
    
    [self addSubview:[LoadingUI LoadingView:self.superview.bounds.size.width SetHeight:self.superview.bounds.size.height]];
    [self addSubview:[LoadingUI LoadingImage:self.superview.bounds.size.width SetHeight:self.superview.bounds.size.height]];
}

-(void)threadStopAnimating {
    
    [[NSOperationQueue mainQueue] addOperationWithBlock:
     ^(void) {
         [[self viewWithTag:LOADINGVIEW_TAG] removeFromSuperview];
         [[self viewWithTag:LOADINGIMAGE_TAG] removeFromSuperview];
     }];
}

@end
